package com.zsd.android.common.retrofit

import android.net.ParseException
import com.google.gson.JsonSyntaxException
import com.google.gson.stream.MalformedJsonException
import io.reactivex.exceptions.CompositeException
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException

object FactoryException {

    private val HttpException_MSG = "网络异常"
    private val ConnectException_MSG = "服务器连接错误";
    private val JSONException_MSG = "数据格式错误"
    private val UnknownHostException_MSG = "无法解析该域名";
    private val UNKNOWN_ERROR_MSG = "未知错误"

    /*网络错误*/
    private val NETWORD_ERROR_CODE = 0x1
    /*http_错误*/
    private val HTTP_ERROR_CODE = 0x2
    /*json错误*/
    private val JSON_ERROR_CODE = 0x3
    /*未知错误*/
    private val UNKNOWN_ERROR_CODE = 0x4
    /*运行时异常-包含自定义异常*/
    private val RUNTIME_ERROR_CODE = 0x5
    /*无法解析该域名*/
    private val UNKOWNHOST_ERROR_CODE = 0x6
    /*非法状态异常*/
    private val UNKNOWN_STATUS_CODE = 0x7
    /*缓存文件异常*/
    private val CACHE_ERROR_CODE = 0x8

    fun analysisException(e: Throwable) : ApiException {
        val apiException = ApiException(e)
        if (e is HttpException) {
            //网络异常
            apiException.code = HTTP_ERROR_CODE
            apiException.msg = HttpException_MSG
        } else if (e is ConnectException || e is SocketTimeoutException) {
            //连接异常
            apiException.code = HTTP_ERROR_CODE
            apiException.msg = ConnectException_MSG
        } else if (e is JsonSyntaxException || e is JSONException || e is ParseException) {
            //解析异常
            apiException.code = JSON_ERROR_CODE
            apiException.msg = JSONException_MSG
        } else if (e is UnknownHostException) {
            //无法解析域名异常
            apiException.code = UNKOWNHOST_ERROR_CODE
            apiException.msg = UnknownHostException_MSG
        } else if (e is CompositeException) {
            for (throwable in e.exceptions) {
                if (throwable is SocketTimeoutException || e is ConnectException) {
                    apiException.code = HTTP_ERROR_CODE
                    apiException.msg = ConnectException_MSG
                } else if (throwable is UnknownHostException) {
                    apiException.code = UNKOWNHOST_ERROR_CODE
                    apiException.msg = UnknownHostException_MSG
                } else if (throwable is MalformedJsonException) {
                    apiException.code = JSON_ERROR_CODE
                    apiException.msg = JSONException_MSG
                }
            }
        } else {
            //未知异常
            apiException.code = UNKNOWN_ERROR_CODE
            apiException.msg = UNKNOWN_ERROR_MSG
        }
        return apiException
    }
}